package com.huanong.it.xwadmin.authority.common.utils;

import com.huanong.it.xwadmin.authority.common.entity.MyConst;
import com.huanong.it.xwadmin.authority.common.exception.JwtExpiredException;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {
    @Value("${jwt.secret}")
    private String jwtSecret;
    @Value("${jwt.expiration}")
    private long jwtExpiration;

    @Autowired
    private RedisUtil redisUtil;



    public String genJwt(String username){
        Date now = new Date();
        Date expiration = new Date(now.getTime() + jwtExpiration*1000*60);

        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256, jwtSecret);
        String jwt = builder.compact();
        redisUtil.set(username+ MyConst.TOKEN, jwt, jwtExpiration*1000*60);
        return jwt;

    }

    public boolean isExpired(String jwt){
        return !redisUtil.hasKey(jwt);
    }

    public Claims parseJwt(String jwt) throws JwtExpiredException {
        Claims claims = Jwts
                .parser()
                .setSigningKey(jwtSecret)
                .parseClaimsJws(jwt)
                .getBody();
        if(isExpired(claims.getSubject()+MyConst.TOKEN)){
            throw new ExpiredJwtException(null, null, "Token expired");
        }
        return claims;
    }
}
